/*
 * Thread class that checks one COM Port for the client and 
 * if found returns it to the ClientFinder Class
*/

package com.costeaalex.blueserver.comm;

import java.io.IOException;
import java.io.InputStream;

import javax.comm.CommPort;

public class COMPortClientCheck extends Thread
	{
	
	private InputStream iS;
	private int reads=0;
	private byte[] data;
	private COMPortClientFinder cFL;
	private CommPort cPL;
	
	public COMPortClientCheck(COMPortClientFinder cF, CommPort cP, String name)
		{
		super(name);
		try
			{
			iS=cP.getInputStream();
			} 
		catch (IOException e)
			{
			e.printStackTrace();
			}
		cPL=cP;
		cFL=cF;
		}
	
	public void run()
		{
		while(true)
			{
			data=new byte[4];
			try
				{
				iS.read(data);
				if(data[0]==1 && data[1]==0 && data[2]==0 && data[3]==2)
					reads++;
				if(reads>=5)
					{
					cFL.foundPort(cPL);
					break;
					}
				}
			catch (Exception e)
				{
				//e.printStackTrace();
				}
			}
		}
	
	public void closePort()
		{
		if(cPL!=null)
			{
			cPL.close();
			interrupt();
			System.out.println(cPL.getName()+" closed");
			}
		}
	}
